import { defineStore } from "pinia";
import request from "@/utils/request";

import { ApiRes } from "@/types/data";
import { CartItem } from "@/types/cart";
import { ITEM_RENDER_EVT } from "element-plus/es/components/virtual-list/src/defaults";

export default defineStore({
  id: "cart",
  state: () => {
    return {
      list: [] as CartItem[],
    };
  },
  getters: {
    // 是否全选
    isAllSelect (): boolean {
      return (
        this.list.length > 0 && this.list.every(item => item.selected)
      )
    },
    // 获取商品总数
    totalCount(): number {
      return this.list.length
    },

    // 获取选中的商品数量
    selectedTotal(): number {
      return this.list.filter(item => item.selected).length
    },

    // 获取选中的总金额
    selectedAmount(): string {
      // return this.list.filter(item => item.selected).reduce((sum, item) => sum + Number(item.nowPrice) * item.count, 0)
      return this.list.filter(item => item.selected).reduce((sum, item) => sum + Number(item.nowPrice) * item.count, 0).toFixed(2)
    }
  },
  actions: {
    // 实现全选或是反选
    async selectAll(selected: boolean) {
      await request.put('/member/cart/selected', {
        selected
      })

      // 重新获取
      this.getCartList()
    },

    async addToCart(data: { skuId: string; count: number }) {
      await request.post("/member/cart", data);
    },
    // 获取购物车列表数据
    async getCartList() {
      const res = await request.get<ApiRes<CartItem[]>>("/member/cart");

      this.list = res.data.result;
    },

    // 删除购物车
    async delCart(ids: string[]) {
      await request.delete("/member/cart", {
        data: {
          ids,
        },
      });

      // 重新获取
      this.getCartList();
    },

    // 修改购物车
    async updateCart(
      skuId: string,
      data: { selected?: boolean; count?: number }
    ) {
      await request.put(`/member/cart/${skuId}`, data);

      // 重新获取
      this.getCartList();
    },
  },
});
